package sz.szsmk.citizencard.ui.newversion.fragment.presenter

import android.util.Log
import com.google.gson.Gson
import com.youzan.spiderman.utils.MD5Utils
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import sz.szsmk.citizencard.DaggerApplication
import sz.szsmk.citizencard.model.network.bean.request.*
import sz.szsmk.citizencard.model.network.bean.response.*
import sz.szsmk.citizencard.model.network.clarkbean.response.AreaInfoResponse
import sz.szsmk.citizencard.model.network.dzbean.req.CommonRequest
import sz.szsmk.citizencard.model.network.dzbean.req.GetOpenIdReq
import sz.szsmk.citizencard.model.network.dzbean.res.CheckIsRealName2Res
import sz.szsmk.citizencard.model.network.dzbean.res.GetOpenIdRes
import sz.szsmk.citizencard.mvp.dzsmkpresenter.AppBasePresenter
import sz.szsmk.citizencard.retrofitrxjava.newversion.ApiCallback
import sz.szsmk.citizencard.retrofitrxjava.newversion.HttpDateSource
import sz.szsmk.citizencard.retrofitrxjava.newversion.NewHttpApi
import sz.szsmk.citizencard.retrofitrxjava.newversion.SubscriberCallBack
import sz.szsmk.citizencard.smkretrofit.NetworkDateSource
import sz.szsmk.citizencard.ui.newversion.fragment.view.HomeMvpView
import sz.szsmk.citizencard.util.ACache
import sz.szsmk.citizencard.util.AndroidUtils
import sz.szsmk.citizencard.util.Constant
import sz.szsmk.citizencard.util.ObjectSignatureUtil
import java.util.*
import javax.inject.Inject


/**
 *  author : hyt
 *  date : 2020/9/2
 *  description :
 */
class HomePresenter@Inject constructor(var httpDateSourceNotUse: NetworkDateSource):
    AppBasePresenter<HomeMvpView>() {

    //获取首页 模块数据
    fun queryAreaInfo(){

        val baseRequest = IBaseRequest()
        val access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token")
        baseRequest.access_token = access_token
        val androidId = AndroidUtils.getAndroidId(DaggerApplication.getIns())
        baseRequest.device_id = AndroidUtils.getAndroidId(DaggerApplication.getIns())
        val refresh_token = ACache.get(DaggerApplication.getIns()).getAsString("refresh_token")
        val key = "access_token=$access_token&device_id=$androidId&key=$refresh_token"
        val stringMd5 = MD5Utils.getStringMd5(key).toUpperCase()
        baseRequest.sign = stringMd5

        HttpDateSource.createApi()?.getAreaInfo(baseRequest)?.subscribeOn(Schedulers.io())
            ?.observeOn(AndroidSchedulers.mainThread())
            ?.subscribe(SubscriberCallBack(  object : ApiCallback<AreaInfoResponse?> {
                override fun onSuccess(response: AreaInfoResponse?) {
                    response?.let {
                        mvpView.getAreaInfoSuccess(it)
                    }
                }

                override fun onFailure(model: BaseBean?, e: Throwable?) {
                    model?.let { mvpView.onFail(it) }
                }
            }))

    }

    //公告
    fun queryNoticeInfo(){
        val getResourceRes = GetResourceReq()
        getResourceRes.resource_area_id = 42

        addSubscription(HttpDateSource.createApi()?.queryInterductionArea(getResourceRes), object : ApiCallback<QueryInterductionAreaRes?> {
            override fun onSuccess(response: QueryInterductionAreaRes?) {
                response?.let {
                    mvpView.getNoticeInfoSuccess(it)

                }
            }

            override fun onFailure(model: BaseBean?, e: Throwable?) {
                model?.let { mvpView.onFail(it) }
            }
        })
    }

    //获取用户数据
    fun queryUserApp(){
        val baseRequest = IBaseRequest()
        addSubscription(HttpDateSource.createApi()?.queryAllFunctionNew(baseRequest), object : ApiCallback<QueryAllFunctionNewRes?> {
            override fun onSuccess(response: QueryAllFunctionNewRes?) {
                response?.let {
                    mvpView.getUserAppSuccess(it)
                }
            }

            override fun onFailure(model: BaseBean?, e: Throwable?) {
                model?.let { mvpView.onFail(it) }
            }
        })
    }

    //天气
    fun getWeather(){
        val homeWeathReq = HomeWeathReq()
        homeWeathReq.cityName = "苏州"

        addSubscription(HttpDateSource.createApi()?.getWeathGeneral(homeWeathReq), object : ApiCallback<HomeWeathRes?> {
            override fun onSuccess(response: HomeWeathRes?) {
                response?.let {
                    mvpView.getWeatherSuccess(it)
                }
            }

            override fun onFailure(model: BaseBean?, e: Throwable?) {
                model?.let { mvpView.onFail(it) }
            }
        })
    }

    //获取首页消息
    fun getMessageNumber(){
        val noticeMainReq = NoticeMainReq()
        val access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token")
        noticeMainReq.access_token = access_token
        noticeMainReq.sign = "asdf"

        addSubscription(HttpDateSource.createApi()?.getMainNotice(noticeMainReq), object : ApiCallback<NoticeMainres?> {
            override fun onSuccess(response: NoticeMainres?) {
                response?.let {
                    mvpView.getMessageNumberSuccess(it)
                }
            }

            override fun onFailure(model: BaseBean?, e: Throwable?) {
                model?.let { mvpView.onFail(it) }
            }
        })
    }

    //获取拼接字符串 第三方使用
    fun getGetOrderId(){
        val access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token")
        val getOrderOpenid = GetOrderOpenid()
        getOrderOpenid.tag = "HUIMIN"
        getOrderOpenid.access_token = access_token

        addSubscription(HttpDateSource.createApi()?.getOrderOpenid(getOrderOpenid), object : ApiCallback<GetOrderOpenidRes?> {
            override fun onSuccess(response: GetOrderOpenidRes?) {
                response?.let {
                    Constant.EXTENT = response.extend
                }
            }

            override fun onFailure(model: BaseBean?, e: Throwable?) {
                model?.let { mvpView.onFail(it) }
            }
        })
    }

    //获取交通一卡通卡片
    fun queryUserCard(origin: String?) {
        val cardRequest = QueryUserCardRequest()
        val access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token")
        cardRequest.access_token = access_token
        cardRequest.type = "0"
        cardRequest.origin = origin
        val json = Gson().toJson(cardRequest)
        Log.e("queryUserCard->", json)
        addSubscription(HttpDateSource.createApi()?.queryUserCardInfo(cardRequest), object : ApiCallback<QueryUserCardRes?> {
            override fun onSuccess(response: QueryUserCardRes?) {
                //筛检出交通一卡通传给view
                var getCard: Boolean = false;
                for (element0 in response?.data!!) {
                    for (element in element0.cardDetailInfolist) {
                        if (("江苏交通一卡通") == element.cardTypeName) {
                            response.let {
                                mvpView.getBindTrafficCardSuccess(element0);//将卡数据传给view
                                getCard = true
                            }

                        }
                    }
                }
                if (!getCard) {
                    response.let {
                        mvpView.getBindTrafficCardFail(it);//将卡数据传给view
                    }
                }
            }

            override fun onFailure(response: BaseBean?, e: Throwable?) {
                response.let {
                    mvpView.getBindTrafficCardFail(it);
                }
            }

        })

    }

    //nfc记录信息
    fun saveNfcCard(cardNo: List<AddNfcCardInfo>?, deviceID: String?){
        val saveNfcCardReq = SaveNfcCardReq()
        val access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token")
        saveNfcCardReq.accessToken = access_token
        saveNfcCardReq.cards=cardNo
        saveNfcCardReq.deviceToken=deviceID
        val json = Gson().toJson(saveNfcCardReq)
        Log.e("saveNfcCardReq->", json)
        addSubscription(HttpDateSource.createApi()?.saveNfcCardInfo(saveNfcCardReq), object : ApiCallback<BaseBean?> {
            override fun onSuccess(response: BaseBean?) {

                mvpView.saveNfcCardSuccess(response)
            }

            override fun onFailure(model: BaseBean?, e: Throwable?) {
                mvpView.saveNfcCardFail(model)
            }

        })
    }

    //新接口
    fun getOpenID(tag: String?){
        val getOpenIDReq=GetOpenIDReq()
        val access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token")
        getOpenIDReq.access_token=access_token
        getOpenIDReq.tag=tag
        val json = Gson().toJson(getOpenIDReq)
        Log.e("getopenid->", json)
        addSubscription(HttpDateSource.createApi()?.getOpenID(getOpenIDReq), object : ApiCallback<GetOpenIDRes?> {
            override fun onSuccess(response: GetOpenIDRes?) {
                mvpView.getOpenIDSuccess(response)
            }

            override fun onFailure(model: BaseBean?, e: Throwable?) {
                //mvpView.saveNfcCardFail(model)
            }

        })
    }

    //获取首页悬浮广告
    fun showADInfo(deviceID: String?, sign: String?){
        val showADReq=ShowADReq()
        val access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token")
        showADReq.access_token=access_token
        showADReq.device_id=deviceID
        showADReq.sign=sign
        val json = Gson().toJson(showADReq)
        Log.e("getopenid->", json)
        addSubscription(HttpDateSource.createApi()?.showAD(showADReq), object : ApiCallback<ShowADRes?> {
            override fun onSuccess(response: ShowADRes?) {
                mvpView.getShowADSuccess(response)
            }

            override fun onFailure(model: BaseBean?, e: Throwable?) {
                //mvpView.saveNfcCardFail(model)
            }

        })
    }



    //仅仅为了查询是否开通公交码。
    fun openID(access_token: String){
        val getOpenIdReq = GetOpenIdReq()
        getOpenIdReq.user_type = 0
        getOpenIdReq.access_token = access_token
        addSubscription(HttpDateSource.createApi()?.getOpenId(getOpenIdReq), object : ApiCallback<GetOpenIdRes?> {
            override fun onSuccess(response: GetOpenIdRes?) {
                response?.let {
                    checkisRealNmae(it)

                }
            }

            override fun onFailure(model: BaseBean?, e: Throwable?) {
                model?.let { mvpView.onFail(it) }
            }
        })
    }

    //查询是否实名  这里的实名 和 外面的L2实名  不是一个概念
    fun checkisRealNmae(getOpenIdRes: GetOpenIdRes){
        val request = CommonRequest()
        request.openId = getOpenIdRes.openId
        ObjectSignatureUtil.signaturePreAuthRequest(request)
        addSubscription(HttpDateSource.createApi(NewHttpApi::class.java, Constant.DZ_BASE_URL)?.checkIsRealName(request),
            object : ApiCallback<CheckIsRealName2Res?> {
                override fun onSuccess(response: CheckIsRealName2Res?) {
                    response?.let {
                        //实名判断
                        val isRealName: String = response.data.isRealName
                        ACache.get(DaggerApplication.getIns()).put("isRealName",isRealName)
                        //0 未实名 1实名
                        if (isRealName == "0") {
                            //签协议

                        } else if (isRealName == "1") {
                            ACache.get(activity).put("bus_register","1")
                            //如果实名  获取 和那个银行签的协议   建设银行 000003

                        }
                    }
                }

                override fun onFailure(model: BaseBean?, e: Throwable?) {
                    model?.let { mvpView.onFail(it) }
                }
            })
    }

    //校验桂花分账号是否存在
    fun accountExist(level :String?,idCard :String?,phoneNum :String?,realName :String?){
        val accountExist= AccountExistReq()
        if (level.equals("1.0")){
            accountExist.authenticationLevel="L3"
            accountExist.idCard=idCard
            accountExist.phoneNum=phoneNum
            accountExist.realName=realName
            addSubscription(HttpDateSource.createApi()?.queryAccountExist(accountExist), object : ApiCallback<AccountExistRes?> {
                override fun onSuccess(response: AccountExistRes?) {
                    response?.let {
                        Log.e("queryAccountExist",response.msg)
                        Log.e("queryAccountExist","进入LV3")
                        mvpView.accountExist(it)
                    }
                }
                override fun onFailure(model: BaseBean?, e: Throwable?) {}
            })
        }else{
            accountExist.phoneNum=phoneNum
            accountExist.authenticationLevel="LV1"
            addSubscription(HttpDateSource.createApigfh()?.queryAccountExist(accountExist), object : ApiCallback<AccountExistRes?> {
                override fun onSuccess(response: AccountExistRes?) {
                    response?.let {
                        Log.e("queryAccountExist",response.msg)
                        Log.e("queryAccountExist","进入LV1 2")
                        mvpView.accountExist(it)
                    }
                }
                override fun onFailure(model: BaseBean?, e: Throwable?) {
                }
            })
        }
    }


    fun getHomeData(){


    }


}